package com.gzs.learn.admin.web.controller.payment;

import com.gzs.learn.admin.common.annotation.Log;
import com.gzs.learn.admin.common.core.controller.BaseController;
import com.gzs.learn.admin.common.core.page.TableDataInfo;
import com.gzs.learn.admin.common.enums.BusinessType;
import com.gzs.learn.admin.common.enums.PayCertType;
import com.gzs.learn.admin.common.utils.bean.BeanUtils;
import com.gzs.learn.admin.model.vo.request.PaymentChannelCfgRequest;
import com.gzs.learn.common.AjaxResult;
import com.gzs.learn.common.util.JsonUtil;
import com.gzs.learn.inf.PageResponseDto;
import com.gzs.learn.inf.enums.StatusEnums;
import com.gzs.learn.payment.inf.IPaymentWebClientSign;
import com.gzs.learn.payment.inf.IPaymentWebQueryClientSign;
import com.gzs.learn.payment.inf.dto.web.PaymentChannel;
import com.gzs.learn.payment.inf.dto.web.PaymentChannel.PubPrivPair;
import com.gzs.learn.payment.inf.dto.web.req.PaymentChannelSearchDto;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

/**
 * 支付配置Controller
 *
 * @author guanzhisong
 * @date 2021-08-25
 */
@RestController
@RequestMapping("/system/payment_config")
@RequiredArgsConstructor
public class PaymentChannelConfigController extends BaseController {
    private final IPaymentWebClientSign iPaymentWebClientSign;
    private final IPaymentWebQueryClientSign iPaymentWebQueryClientSign;

    /**
     * 查询支付配置列表
     */
    @PreAuthorize("@ss.hasPermi('payment:config:list')")
    @GetMapping("/list")
    public TableDataInfo list(PaymentChannelSearchDto searchDto) {
        PageResponseDto<PaymentChannel> responseDto = iPaymentWebQueryClientSign.searchChannelList(searchDto);
        return getDataTable(responseDto);
    }

    /**
     * 获取支付配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('payment:config:list')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(iPaymentWebQueryClientSign.channelDetail(id));
    }

    /**
     * 新增支付配置
     *
     * @throws IOException
     */
    @PreAuthorize("@ss.hasPermi('payment:config:edit')")
    @Log(title = "支付配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(PaymentChannelCfgRequest request) throws IOException {
        PaymentChannel channel = new PaymentChannel();
        BeanUtils.copyProperties(request, channel);
        if (request.getCertType() == PayCertType.STRING_CERT.getCode()) {
            PubPrivPair pair = new PubPrivPair();
            pair.setPub(request.getPubKey());
            pair.setPriv(request.getPrivKey());
            pair.setType(PayCertType.STRING_CERT.getCode());

            channel.setPkcsContent(JsonUtil.toJSONString(pair));
        } else if (request.getCertType() == PayCertType.FILE_CERT.getCode()) {
            MultipartFile pkcs = request.getPkcs();
            if (pkcs == null || pkcs.getBytes().length == 0) {
                return AjaxResult.error("证书为空");
            }
            String pkcsContent = new String(Base64.getEncoder().encode(pkcs.getBytes()));
            String pkcsPwd = request.getPkcsPwd();
            PubPrivPair pair = new PubPrivPair();
            pair.setCertContent(pkcsContent);
            pair.setCertPwd(pkcsPwd);
            pair.setType(PayCertType.FILE_CERT.getCode());

            channel.setPkcsContent(JsonUtil.toJSONString(pair));
        }
        return AjaxResult.success(iPaymentWebClientSign.addPaymentChannel(channel));
    }

    /**
     * 修改支付配置
     *
     * @throws IOException
     */
    @PreAuthorize("@ss.hasPermi('payment:config:edit')")
    @Log(title = "支付配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(PaymentChannelCfgRequest request) throws IOException {
        PaymentChannel channel = new PaymentChannel();
        BeanUtils.copyProperties(request, channel);
        if (request.getCertType() == PayCertType.STRING_CERT.getCode()) {
            if (StringUtils.isBlank(request.getPubKey()) || StringUtils.isBlank(request.getPrivKey())) {
                return AjaxResult.error("公钥/私钥不匹配");
            }
            PubPrivPair pair = new PubPrivPair();
            pair.setPub(request.getPubKey());
            pair.setPriv(request.getPrivKey());
            pair.setType(PayCertType.STRING_CERT.getCode());

            channel.setPkcsContent(JsonUtil.toJSONString(pair));
        } else if (request.getCertType() == PayCertType.FILE_CERT.getCode()) {
            MultipartFile pkcs = request.getPkcs();
            if (pkcs == null || pkcs.getBytes().length == 0) {
                return AjaxResult.error("证书为空");
            }
            String pkcsContent = new String(Base64.getEncoder().encode(pkcs.getBytes()));
            String pkcsPwd = request.getPkcsPwd();
            PubPrivPair pair = new PubPrivPair();
            pair.setCertContent(pkcsContent);
            pair.setCertPwd(pkcsPwd);
            pair.setType(PayCertType.FILE_CERT.getCode());

            channel.setPkcsContent(JsonUtil.toJSONString(pair));
        }

        return AjaxResult.success(iPaymentWebClientSign.updatePaymentChannel(channel));
    }

    /**
     * 修改支付配置
     */
    @PreAuthorize("@ss.hasPermi('payment:config:edit')")
    @Log(title = "支付配置", businessType = BusinessType.UPDATE)
    @PostMapping("change_status")
    public AjaxResult changeStatus(Long id, Integer status) {
        PaymentChannel channel = new PaymentChannel();
        channel.setId(id);
        channel.setStatus(status);
        return AjaxResult.success(iPaymentWebClientSign.updatePaymentChannel(channel));
    }

    /**
     * 删除支付配置
     */
    @PreAuthorize("@ss.hasPermi('payment:config:edit')")
    @Log(title = "支付配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        PaymentChannel channel = new PaymentChannel();
        channel.setId(id);
        channel.setStatus(StatusEnums.DELETE.getCode());
        return AjaxResult.success(iPaymentWebClientSign.updatePaymentChannel(channel));
    }
}
